package com.web.web.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
public class HttpApiImpl implements HttpApi {


    private final HttpClient httpClient;
    private HttpUriRequest httpRequest;

    public HttpApiImpl() {
        this.httpClient = HttpClients.createDefault();
    }

    @Override
    public String doGet(String url, Map<String, String> headerParams) {
        HttpGet httpGet = new HttpGet(url);
        if (headerParams != null) {
            for (Map.Entry<String, String> entry : headerParams.entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }
        }
        this.httpRequest = httpGet;
        return execute();
    }

    @Override
    public String doPost(String url, Map<String, String> headerParams, Map<String, String> params) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        if (headerParams != null) {
            for (Map.Entry<String, String> entry : headerParams.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        List<BasicNameValuePair> param = new ArrayList<>();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(param, "UTF-8"));
        }
        this.httpRequest = httpPost;
        return execute();
    }


    public String execute() {
        try {
            HttpResponse response = httpClient.execute(httpRequest);
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            log.error(e + ":" + e.getMessage());
            return "失败";
        }
    }
}
